package org.rooster.service;

import org.jgap.Gene;
import org.jgap.IChromosome;
import org.rooster.dbmanager.repository.RoosterRepository;
import org.rooster.encoder.Encoder;
import org.rooster.genetic.GeneIndex;
import org.rooster.manager.ResourceTypeInterface;
import org.rooster.manager.TaskManager;
import org.rooster.schedule.*;
import org.rooster.JGAPMain;

/**
 *
 * @author Renukshan
 */
public class ScheduleService {

    /**
     * save the schedule in the database
     * @param bestSolutionSoFar
     */
    public static void insertRecordsToDatabase(IChromosome bestSolutionSoFar) {

        RoosterRepository.getInstance().clearScheduleTable();
        Gene[] genes = bestSolutionSoFar.getGenes();
        ResourceAllocation resourceAllocation;
        int start, end;
        for (int i = 0; i < TaskManager.NO_OF_SECTIONS; i++) {
            for (int j = 0; j < TaskManager.NO_OF_TIME_SLOTS; j++) {
                for (int k = 0; k < ResourceTypeInterface.NO_OF_RESOURCE_TYPES; k++) {
                    start = GeneIndex.getResourceTypeStart(i, j, k);
                    end = GeneIndex.getResourceTypeEnd(i, j, k);
                    for (int l = start; l <= end; l++) {
                        resourceAllocation = new ResourceAllocation();
                        resourceAllocation.setResourceId(Encoder.getInstance().getResourceId((Integer) genes[l].getAllele(), k));
                        resourceAllocation.setResourceTypeId(k);
                        resourceAllocation.setTaskId(i);
                        resourceAllocation.setTimeSlotId(j);

                        RoosterRepository.getInstance().insertResourceAllocation(resourceAllocation);

                    }
                }
            }
        }
    }

    /**
     * set the termination parameters from the view layer
     * @param fitnessSelected
     * @param fitness
     * @param timeSelected
     * @param time
     * @param progressWithinTimeSelected
     * @param progressWithinIterationsSelected
     * @param noOfIterations
     */
    public void setTerminationParamerts(boolean fitnessSelected, int fitness, boolean timeSelected, int time, boolean progressWithinTimeSelected, boolean progressWithinIterationsSelected, int noOfIterations) {

        JGAPMain jgapMain = new JGAPMain();
        jgapMain.setParameters(fitnessSelected, fitness, timeSelected, time, progressWithinTimeSelected, progressWithinIterationsSelected, noOfIterations);
    }

    public void setResourceCapability(ResourceCapability resourceCapability) {

        RoosterRepository.getInstance().updateResourceCapability(resourceCapability);


    }
}
